package com.xinqi.modules.exam.student.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.google.common.collect.ImmutableMap;
import com.xinqi.common.base.dto.QuestionBaseDTO;
import com.xinqi.common.base.enums.QuestionTypeEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.response.R;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.exam.common.constants.ExamI18nConstants;
import com.xinqi.modules.exam.common.error.ExamErrors;
import com.xinqi.modules.exam.paper.domain.CourseExamPaperEntity;
import com.xinqi.modules.exam.paper.enums.ExamStatusEnum;
import com.xinqi.modules.exam.paper.manager.CourseExamPaperManager;
import com.xinqi.modules.exam.student.convert.CourseExamPaperErrorSetConvert;
import com.xinqi.modules.exam.student.domain.CourseExamPaperErrorSetEntity;
import com.xinqi.modules.exam.student.domain.CourseExamPaperStudentEntity;
import com.xinqi.modules.exam.student.dto.PaperAnswerDTO;
import com.xinqi.modules.exam.student.dto.req.CourseExamPaperErrorSetCreateDTO;
import com.xinqi.modules.exam.student.dto.req.CourseExamPaperErrorSetDeleteDTO;
import com.xinqi.modules.exam.student.dto.req.CourseExamPaperErrorSetQueryDTO;
import com.xinqi.modules.exam.student.dto.req.CourseExamPaperErrorSetUpdateDTO;
import com.xinqi.modules.exam.student.dto.rsp.CourseExamPaperErrorSetResultDTO;
import com.xinqi.modules.exam.student.dto.rsp.CourseExamPaperErrorSetStatsDTO;
import com.xinqi.modules.exam.student.enums.PaperErrorSetTypeEnum;
import com.xinqi.modules.exam.student.manager.CourseExamPaperErrorSetManager;
import com.xinqi.modules.exam.student.manager.CourseExamPaperStudentManager;
import com.xinqi.modules.exam.student.service.CourseExamPaperErrorSetService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 课程测评学生错题集服务层实现
 *
 * @author: linkai
 * @date: 2023/07/02
 */
@Validated
@Service("courseExamPaperErrorSetService")
@RequiredArgsConstructor
public class CourseExamPaperErrorSetServiceImpl implements CourseExamPaperErrorSetService {
    private final CourseExamPaperErrorSetConvert courseExamPaperErrorSetConvert;
    private final CourseExamPaperErrorSetManager courseExamPaperErrorSetManager;
    private final CourseExamPaperStudentManager courseExamPaperStudentManager;
    private final CourseExamPaperManager courseExamPaperManager;

    private final ClassStudentClient classStudentClient;


    /**
     * 分页查询 课程测评学生错题集数据
     */
    @Override
    @DS("slaver")
    public PageInfo<CourseExamPaperErrorSetResultDTO> page(Param pageable, CourseExamPaperErrorSetQueryDTO query) {

        // 获取主学生信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(query.getClassId(), query.getStudentId()));
        if (Objects.nonNull(mainStudent)) {
            query.setStudentId(mainStudent.getStudentId());
        }

        IPage<CourseExamPaperErrorSetEntity> page = courseExamPaperErrorSetManager.page(
            Pages.page(pageable, OrderItem.desc(Pages.ID)), wrapper(query)
        );
        ImmutableMap.Builder<Long, Long> questionIdMap = ImmutableMap.builder();
        if (query.getType() != null) {
            List<Long> questionIdList = page.getRecords().stream().map(CourseExamPaperErrorSetEntity::getQuestionId).collect(Collectors.toList());
            PaperErrorSetTypeEnum tempType = Objects.equals(query.getType(), PaperErrorSetTypeEnum.错题集) ? PaperErrorSetTypeEnum.星标题 : PaperErrorSetTypeEnum.错题集;
            courseExamPaperErrorSetManager.findIdByQuestionIdsAndType(
                query.getStudentId(), questionIdList, tempType,
                v -> questionIdMap.put(v.getQuestionId(), v.getId())
            );
        }
        Map<Long, CourseExamPaperStudentEntity> paperStudentMap = new HashMap<>(page.getRecords().size());
        // questionId, id
        ImmutableMap<Long, Long> map = questionIdMap.build();
        return Pages.convert(page, v -> {
            CourseExamPaperErrorSetResultDTO dto = courseExamPaperErrorSetConvert.convert(v);
            dto.init(map.get(dto.getQuestionId()));
            // 获取用户答案
            CourseExamPaperStudentEntity studentPaper = paperStudentMap.get(v.getExamPaperId());
            if (studentPaper == null) {
                studentPaper = courseExamPaperStudentManager.findByExamIdAndStudentId(dto.getExamPaperId(), dto.getStudentId());
                paperStudentMap.put(studentPaper.getExamPaperId(), studentPaper);
            }
            PaperAnswerDTO paperAnswer = studentPaper.findPaperAnswer(dto.getQuestionId());
            if (paperAnswer != null) {
                dto.setStudentAnswer(paperAnswer.getStudentAnswer());
                dto.setStudentAnswerFiles(paperAnswer.getStudentAnswerFiles());
            }
            return dto;
        });
    }

    /**
     * 查询 课程测评学生错题集数据
     */
    @Override
    public List<CourseExamPaperErrorSetResultDTO> find(CourseExamPaperErrorSetQueryDTO query) {
        return courseExamPaperErrorSetManager.list(wrapper(query)).stream()
            .map(courseExamPaperErrorSetConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<CourseExamPaperErrorSetEntity> wrapper(CourseExamPaperErrorSetQueryDTO query) {
        LambdaQueryWrapper<CourseExamPaperErrorSetEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getId, v));
        Queries.accept(query.getClassId(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getClassId, v));
        Queries.accept(query.getExamId(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getExamPaperId, v));
        Queries.accept(query.getStudentId(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getStudentId, v));
        Queries.accept(query.getQuestionType(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getQuestionType, v.getCode()));
        Queries.accept(query.getQuestionId(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getQuestionId, v));
        Queries.accept(query.getType(), v -> wrapper.eq(CourseExamPaperErrorSetEntity::getType, v.getCode()));
        return wrapper;
    }

    /**
     * 根据id查询 课程测评学生错题集数据
     */
    @Override
    public CourseExamPaperErrorSetResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(courseExamPaperErrorSetManager.findById(id)).map(courseExamPaperErrorSetConvert::convert).orElse(null);
    }

    /**
     * 新增 课程测评学生错题集数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid CourseExamPaperErrorSetCreateDTO dto) {

        // 获取试题信息
        CourseExamPaperEntity courseExamPaper = Optional.ofNullable(courseExamPaperManager.findById(dto.getExamPaperId()))
            .orElseThrow(() -> ExamErrors.EXAM_NOT_EXIST.asException(ExamI18nConstants.测评不存在));
        CommonErrors.BAD_REQUEST.check(Objects.equals(courseExamPaper.getStatus(), ExamStatusEnum.已结束), "测评必须结束才能添加错题");

        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(courseExamPaper.getClassId(), dto.getStudentId()));
        if (Objects.nonNull(mainStudent)) {
            dto.setStudentId(mainStudent.getStudentId());
        }

        // 判断题目是否存在
        CommonErrors.BAD_REQUEST.check(!courseExamPaperErrorSetManager.isExist(dto.getStudentId(), dto.getType(), dto.getQuestionId())
            , "请勿重复添加");

        QuestionBaseDTO question = Optional.ofNullable(courseExamPaperManager.findQuestionById(courseExamPaper, dto.getQuestionId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("题目不存在"));

        CourseExamPaperErrorSetEntity entity = courseExamPaperErrorSetConvert.create(dto);
        entity.setClassId(courseExamPaper.getClassId());
        entity.setQuestionType(QuestionTypeEnum.of(question.getType()));
        entity.setQuestion(question);
        courseExamPaperErrorSetManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 课程测评学生错题集数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid CourseExamPaperErrorSetUpdateDTO dto) {
        Optional.ofNullable(courseExamPaperErrorSetManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        QuestionBaseDTO question = Optional.ofNullable(courseExamPaperManager.findQuestionById(dto.getExamPaperId(), dto.getQuestionId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("题目不存在"));
        CourseExamPaperErrorSetEntity entity = courseExamPaperErrorSetConvert.update(dto);
        entity.setQuestion(question);
        return courseExamPaperErrorSetManager.updateById(entity);
    }

    /**
     * 根据id删除 课程测评学生错题集数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return courseExamPaperErrorSetManager.deleteById(id);
    }

    /**
     * 根据id删除 课程测评学生错题集数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(CourseExamPaperErrorSetDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    public CourseExamPaperErrorSetStatsDTO statsData(CourseExamPaperErrorSetQueryDTO dto) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getClassId()), "班级ID不能为空");
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getStudentId()), "学生ID不能为空");

        // 获取主学生信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(dto.getClassId(), dto.getStudentId()));
        if (Objects.nonNull(mainStudent)) {
            dto.setStudentId(mainStudent.getStudentId());
        }

        return courseExamPaperErrorSetManager.statsData(dto);
    }

}
